package com.shortlink.gateway.util;

import cn.hutool.json.JSONUtil;
import com.shortlink.common.base.Result;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 过滤器工具类
 *
 * @author wp
 */
public class FilterUtils {
    public static Mono<Void> returnJson(ServerWebExchange exchange, Result<?> result) {
        String resultJson = JSONUtil.toJsonStr(result);

        DataBufferFactory factory = exchange.getResponse().bufferFactory();
        byte[] bytes = resultJson.getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = factory.allocateBuffer(bytes.length);
        buffer.write(bytes);

        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
        return exchange.getResponse().writeWith(Mono.just(buffer));
    }
}
